package logic

import (
	"context"
	"errors"
	"local-life/cache"
	"local-life/model"

	"local-life/liferpc/internal/svc"
	"local-life/liferpc/liferpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *liferpc.CartAddRequest) (*liferpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var goods model.Good
	err := cache.CartExists(goods.Stock)
	if err != nil {
		return nil, errors.New("库存不足")
	}
	goodMap := map[string]interface{}{
		"StoreID": goods.StoreID,
		"Name":    goods.Name,
		"Price":   goods.Price,
		"Stock":   goods.Stock,
		"Img":     goods.Img,
		"Total":   goods.Total,
	}
	err = cache.CartCreate(int(in.UserID), int(in.GoodID), goodMap)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	return &liferpc.CartAddResponse{
		Success: true,
		Data:    "添加成功",
	}, nil
}
